@extends('layouts.app')

@section('title', '餐饮商家列表')

@section('css-import')
<link href="{{config('app.inlet_src')}}/assets/css/bootstrap-datetimepicker.min.css" rel="stylesheet" media="screen">
<!-- <link rel="stylesheet" type="text/css" href="{{config('app.inlet_src')}}/assets/css/htmleaf-demo.css"> -->
<link rel="stylesheet" href="{{config('app.inlet_src')}}assets/css/baguetteBox.min.css">
<!-- <link rel="stylesheet" href="{{config('app.inlet_src')}}/assets/css/gallery-grid.css"> -->
<style type="text/css">
	.identitycardimg_sty{
		width:300px;
		display:block;
	}
	.qrcodeimg{
		cursor:pointer;
	}
	.page-s{
		display: inline-block;
		padding-bottom: 0px;
		margin: 29px 9px;
		border-radius: 4px;
		float:  right;
	}
	#l-map{height:550px;width:100%;}
#r-result{width:100%;}
#tangram-suggestion--TANGRAM__1h-main{
	z-index: 100000;
}
</style>
@endsection

@section('content-fluid')
<div class="row">
	<!-- BASIC TABLE -->
	<div class="panel">
		<div class="panel-heading">
			<h3 class="panel-title">乐享商家</h3>
		</div>

		<form action="/shopList" method="get">
			<div class="input-group col-md-4 pull-right" style="z-index: auto;">
				<input type="text" value="{{$_GET['shop_name'] ?? ''}}" class="form-control app-search-text" name="shop_name" AUTOCOMPLETE="off" placeholder="搜索商户名">
				@foreach($_GET as $k=>$v)
				@if($k!='page' && $k!='shop_name')
				<input type="hidden" value="{{$v}}" name="{{$k}}">
				@endif
				@endforeach
				<span class="input-group-btn"><button type="submit" class="btn btn-primary search-jslx"><i class="fa fa-search"></i></button></span>
			</div>
		</form>
		<div class="panel-body">
			@if(session('region') < 3) 
			<button class="btn btn-default selectall"  style="float:left;">单页全选</button>
			<button class="btn btn-default companyset"  style="float:left;margin-left:20px;">设置企业商户</button>
			@endif
			<form action="/download/shop/list" method="get">
				<div class="input-group date form_datetime col-md-2" data-date="{{date('Y-m-d H:i')}}" data-date-format="yyyy-mm-dd hh:ii" data-link-field="dtp_input1" style="float:left; margin-left:25px;">
				    <input class="form-control" size="16" type="text" value="{{$_GET['starttime'] ?? ''}}" name="starttime" placeholder="导出从...开始" readonly>
				    <span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>
					<span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
				</div>
				<div class="input-group date form_datetime col-md-2" data-date="{{date('Y-m-d H:i')}}" data-date-format="yyyy-mm-dd hh:ii" data-link-field="dtp_input1" style="float:left; margin-left:20px;">
				    <input class="form-control" size="16" type="text" value="{{$_GET['endtime'] ?? ''}}" placeholder="导出到...结束" name="endtime" readonly>
				    <span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>
					<span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
				</div>
				<button class="btn btn-default" style="margin-left: 20px;" type="submit">导出Excel</button>
			</form>
			<table class="table table-hover">
				<thead>
					<tr>
						@if(session('region') < 3)
						<th></th>
						@endif
						<th>#</th>
						<th>店铺名</th>
						<th>手机号</th>
						<th>入驻时间</th>
						<th>余额</th>
						<th>地址</th>
						<th>状态</th>
						<th>商圈</th>
						@if(isset($_GET['circle_id']))
						<th>圈内排序</th>
						@endif
						<th>结单二维码</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody>
					@foreach($shops as $k=>$v)
					<tr class="shoplist">
						@if(session('region') < 3)
						<td><input type="checkbox" name="select_users[]" value="{{$v->shop_id}}"></td>
						@endif
						<td class="shopid">{{$v->shop_id}}</td>
						<td class="shopname">{{$v->shop_name}}</td>
						<td>{{$v->tel}}</td>
						<td>{{$v->insert_time}}</td>
						<td>{{$v->account}}</td>
						<td style="width:300px;">{{$v->shop_address}}</td>
						<td>{{$v->shop_run_status_text}}</td>
						<td class="circlename">{{$v->circle_name}}</td>
						@if(isset($_GET['circle_id']))
						<td style="width:100px;"><input type="number" name="sort{{$v->shop_id}}" class="circle_sort" value="{{$v->circle_sort}}" style="width:60px;" min="0" data-id="{{$v->shop_id}}"></td>
						@endif
						<td> <a href="javascript:void(0);" onclick="urlClick('{{$v->shop_qrcode}}',this);">二维码</a> </td>
						<td>
							<a href="/shopDetails?shopid={{$v->shop_id}}"><i class="fa fa-info-circle"></i> 查看</a>
							@if(session('region') < 3)
							<a href="javascript:void(0);" onclick="inputClick(this)"><i class="fa fa-info-circle"></i> 商圈</a>
							<a href="javascript:void(0);" onclick="openmapedit('{{$v->shop_id}}','{{$v->shop_position_x}}','{{$v->shop_position_y}}','{{$v->shop_address}}')"><i class="fa fa-info-circle"></i> 精准定位</a>
							@endif
						</td>
					</tr>
					@endforeach
				</tbody>
			</table>
			{{ $shops->appends(['circle_id' => $_GET['circle_id'] ?? '','company_id'=>$_GET['company_id'] ?? '','shop_name'=>$_GET['shop_name'] ?? ''])->links() }}
			<div class="page-s">本页共{{ $shops->count() }}条</div>
			<div class="page-s">共{{ $shops->total() }}条</div>
			<div class="page-s">当前第{{ $shops->currentPage() }}页</div>
			<div class="page-s">共{{ $shops->lastPage() }}页</div>
		</div>
		
	</div>
	<!-- END BASIC TABLE -->
</div>
<div class="modal fade" tabindex="-1" id="exampleModal" role="dialog">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title"></h4>
      </div>
      <form action="/edit/shop/circle" method="post" id="circleEditForm">
	      <div class="modal-body">
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	      </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" tabindex="-1" id="exampleModalMap" role="dialog">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title"></h4>
      </div>
		<form action="/edit/shop/position" method="post" id="positionShopForm">
		  <div class="modal-body">
			  	<div id="l-map"></div>
				<input type="text" id="suggestId" name="address" AUTOCOMPLETE="off" value="" class="form-control limit_days form-input-control" alt="详细地址" placeholder="详细地址">
				<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
				<input type="hidden" name="lat" value="">
				<input type="hidden" name="lng" value="">
				<input type="hidden" name="shop_id" value="">
		  </div>
		  <div class="modal-footer">
		  	<button type="submit" class="btn btn-primary saveCateImage">保存</button>
		    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
		  </div>
		</form>
    </div>
  </div>
</div>
<img src="" class="identitycardimg identitycardimg_sty center-block hide">
@endsection

@section('js-import')
<script type="text/javascript" src="{{config('app.inlet_src')}}assets/scripts/baguetteBox.min.js"></script>
<script src="{{config('app.inlet_src')}}/assets/scripts/bootstrap-datetimepicker.js"></script>
<script src="{{config('app.inlet_src')}}/assets/scripts/bootstrap-datetimepicker.zh-CN.js"></script>
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=vQBEj1uCOLD3MPMwoxrICDUhz7vhyR0e"></script>
@endsection

@section('js-write')
<script type="text/javascript">
	// 百度地图API功能
	function G(id) {
		return document.getElementById(id);
	}

	var map = new BMap.Map("l-map");
	map.addControl(new BMap.NavigationControl());
	map.enableScrollWheelZoom(true);
	map.centerAndZoom("石家庄",21); // 初始化地图，设置城市和地图级别。
	function addbj(lng_,lat_){
		map.clearOverlays();
		var point = new BMap.Point(lng_,lat_);  // 创建点坐标
		map.centerAndZoom(point,23); // 初始化地图,设置城市和地图级别。
		var marker = new BMap.Marker(point)
		marker.enableDragging();
		marker.addEventListener("dragend", function(e){    
		    // alert("当前位置：" + e.point.lng + ", " + e.point.lat); 
		    $('#exampleModalMap').find('input[name="lng"]').val(e.point.lng);
			$('#exampleModalMap').find('input[name="lat"]').val(e.point.lat);
		    addbj(e.point.lng,e.point.lat)
		})
		// polygon.enableEditing();
		// map.addOverlay(polygon);   //增加多边形
		map.addOverlay(marker);    //添加标注
	}
	
	var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
			{"input" : "suggestId","location" : map});

	ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
	var str = "";
		var _value = e.fromitem.value;
		var value = "";
		if (e.fromitem.index > -1) {
			value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		}    
		str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
		
		value = "";
		if (e.toitem.index > -1) {
			_value = e.toitem.value;
			value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		}    
		str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
		G("searchResultPanel").innerHTML = str;
	});

	var myValue;
	ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
	var _value = e.item.value;
		myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
		
		setPlace();
	});

	function setPlace(){
		map.clearOverlays();    //清除地图上所有覆盖物
		function myFun(){
			var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
			var gc = new BMap.Geocoder();
            var pointAdd = new BMap.Point(pp.lng, pp.lat);
            gc.getLocation(pointAdd, function(rs){
                //或者其他信息
                $('input[name="province"]').val(rs.addressComponents.province);
                $('input[name="city"]').val(rs.addressComponents.city);
            })
			setlnglat(pp.lng,pp.lat)
			map.centerAndZoom(pp, 18);
			var marker = new BMap.Marker(pp)
			marker.enableDragging();    
			marker.addEventListener("dragend", function(e){    
			    setlnglat(e.point.lng,e.point.lat);
			})
			map.addOverlay(marker);    //添加标注
		}
		var local = new BMap.LocalSearch(map, { //智能搜索
		  onSearchComplete: myFun
		});
		local.search(myValue);
	}

	function openmapedit(shopid,shop_position_x,shop_position_y,address){
		addbj(shop_position_y,shop_position_x);
		$('#suggestId').val(address);
		$('#exampleModalMap').find('input[name="lng"]').val(shop_position_y);
		$('#exampleModalMap').find('input[name="lat"]').val(shop_position_x);
		$('#exampleModalMap').find('input[name="shop_id"]').val(shopid);
		$('#exampleModalMap').modal();
	}


	$('.form_datetime').datetimepicker({
        language:  'zh-CN',
        weekStart: 1,
        todayBtn:  1,
		autoclose: 1,
		todayHighlight: 1,
		startView: 2,
		forceParse: 0,
        showMeridian: 1
    });
    $(".circle_sort").bind('input porpertychange',function(e){
　　　　	console.log(e.target.value);
		console.log($(this).attr('data-id'))
		$.ajaxSetup({
		    headers: {
		        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
		    }
		});
		$.post('/edit/shop/circle/sort',{'shop_id':$(this).attr('data-id'),'sort':e.target.value},function(response){
			if(response.success){
			}else{
				toastr.error(response.message);
			}
		},'json');
　　　　});
    $('.shoplist').click(function(){
    	var che = !$(this).find('input[name="select_users[]"]').prop('checked');
    	$(this).find('input[name="select_users[]"]').prop('checked',che)
    });
    $('.selectall').click(function(){
    	$('input[type="checkbox"]').each(function(){
    		$(this).prop('checked',!$(this).prop('checked'))
    	})
    });

    $('.companyset').click(function(){
    	var ed = 0;
    	var idar = [];
    	$('#circleEditForm').find('input[name="shop_id[]"]').remove();
    	$('input[name="select_users[]"]').each(function(){
    		if($(this).is(':checked')){
    			idar[ed] = $(this).val();
    			ed = ed+1;
    			$('#circleEditForm').append($('<input type="hidden" name="shop_id[]" value="'+$(this).val()+'">'))
    		}
    	})
    	$('#circleEditForm').attr('action','/edit/shop/company');
    	var modal = $('#exampleModal');
    	modal.find('.modal-body').empty();
    	modal.find('.modal-title').html('选中'+ed+'家商户');
    	var this_ = $('<div class="input-group " style="z-index: auto;"><input type="text" value="" class="form-control app-search-text" name="company_name" AUTOCOMPLETE="off" placeholder="搜索企业"><span class="input-group-btn"><button type="button" class="btn btn-primary search-jslxCompany"><i class="fa fa-search"></i></button></span></div>');
    	modal.find('.modal-body').append($(this_));
    	if(!modal.find('.saveCateImage').length){
	    	modal.find('.modal-footer').append($('<button type="submit" class="btn btn-primary saveCateImage">保存</button>'));
	    }
    	$('#exampleModal').modal();

    	$('.search-jslxCompany').click(function(){
			$.ajaxSetup({
			    headers: {
			        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
			    }
			});
			if($('input[name="shop_id[]"]').length <= 0){
				toastr.error("没有选择商户");
				return false;
			}
			$.post('/search/company',{'company_name':$('#exampleModal').find('input[name="company_name"]').val()},function(response){
				if(response.success){
					$('#exampleModal').find('.modal-body').append($('<hr><p class="lead"><span class="label label-info shop-info-name">'+response.data.company_name+'</span></p> <hr>'));
					$('#circleEditForm').append($('<input type="hidden" name="company_id" value="'+response.data.company_id+'">'))
				}else{
					toastr.error(response.message);
				}
			},'json');
		});
    })
    
	baguetteBox.run('.tz-gallery');
	function urlClick(url,this_l) {
		var this_ = $('<img src="" width="30" title="点击放大" class="qrcodeimg">');
		var modal = $('#exampleModal');
		modal.find('.modal-body').empty();
		modal.find('.modal-title').html($(this_l).parents('tr').find('.shopname').html()+'的二维码');
	    $(this_).attr('src',"{{$qrcodepath}}"+'/'+url).attr('class','identitycardimg identitycardimg_sty center-block');
	    modal.find('.modal-body').append($(this_));
	    modal.find('.saveCateImage').remove();
		$('#exampleModal').modal();
	}
	function inputClick(this_l) {
		var circlename = $(this_l).parents('tr').find('.circlename').html();
		if(circlename=='未设置'){
			circlename = '';
		}
		var this_ = $('<div class="input-group " style="z-index: auto;"><input type="text" value="'+circlename+'" class="form-control app-search-text" name="circle_name" AUTOCOMPLETE="off" placeholder="搜索商圈"><span class="input-group-btn"><button type="button" class="btn btn-primary search-jslx"><i class="fa fa-search"></i></button></span></div>');
		var modal = $('#exampleModal');
		$('#circleEditForm').attr('action','/edit/shop/circle');
		modal.find('.modal-body').empty();
		modal.find('.modal-title').html($(this_l).parents('tr').find('.shopname').html()+'商圈修改');
	    modal.find('.modal-body').append($(this_));
	    modal.find('.modal-body').append($('<input type="hidden" name="shop_id" value="'+$(this_l).parents('tr').find('.shopid').html()+'">'));
	    if(!modal.find('.saveCateImage').length){
	    	modal.find('.modal-footer').append($('<button type="submit" class="btn btn-primary saveCateImage">保存</button>'));
	    }
		$('#exampleModal').modal();
		$('.search-jslx').click(function(){
			$.ajaxSetup({
			    headers: {
			        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
			    }
			});
			$.post('/search/circle',{'circle_name':$('#exampleModal').find('input[name="circle_name"]').val()},function(response){
				if(response.success){
					$('#exampleModal').find('.modal-body').append($('<hr><p class="lead"><span class="label label-info shop-info-name">'+response.data.circle_name+'</span></p> <hr>'));
					$('#circleEditForm').append($('<input type="hidden" name="circle_id" value="'+response.data.circle_id+'">'));
				}else{
					toastr.error(response.message);
				}
			},'json');
		});
	}
	var CouponSendParam = {
	    'dataType':'json',
	    'beforeSubmit':CouponBefore,
	    'success':CouponResponse,
	    'error':toutiaoError,
	};
	function CouponBefore(formData, jqForm, options){
	    
	}
	function CouponResponse(response) {
	    if(response.success){
	        setTimeout(function(){
	            location.href = location.href;
	        },2000);
	        toastr.success(response.message);
	    }else{
	        toastr.error('修改失败，请联系开发人员！');
	    }
	}

	function toutiaoError(XMLHttpRequest, textStatus, errorThrown) {
		if(XMLHttpRequest.status==422){
			var RegError = XMLHttpRequest.responseJSON.errors;
			for(var o in RegError){
				for (var i = 0; i < RegError[o].length; i++) {
					toastr.error(RegError[o][i]);
				}
			}
		}
	}
	ajaxForm_('#circleEditForm', CouponSendParam);
	ajaxForm_('#positionShopForm', CouponSendParam);
</script>	
@endsection